package com.evan.kdl.test.day01;

import com.evan.base.ThreadPoolTaskConfig;
import com.evan.kdl.util.CommonUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class SupplyAsyncExecutorsDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolTaskConfig threadPoolTaskConfig = new ThreadPoolTaskConfig();
        ThreadPoolTaskExecutor threadPoolTaskExecutor = threadPoolTaskConfig.taskExecutor();
        //ExecutorService executor = Executors.newFixedThreadPool(4);
        try {
            CommonUtils.printThreadLog("main start");
            CompletableFuture<String> newsFuture = CompletableFuture.supplyAsync(() -> {
                CommonUtils.printThreadLog("异步读取文件开始");
                String news = CommonUtils.readFile("F:\\idea-workspace-personal\\juc-springboot-demo\\src\\main\\resources\\news.txt");
                CommonUtils.printThreadLog("异步读取文件完成");
                return news;
            }, threadPoolTaskExecutor);
            CommonUtils.printThreadLog("here are not blocked,main continue");
            // 阻塞并等待newsFuture完成
            String news = newsFuture.get();
            CommonUtils.printThreadLog("news = " + news);
            CommonUtils.printThreadLog("main end");
        } finally {
            //注意要关闭线程池
            threadPoolTaskExecutor.shutdown();
        }
    }
}